import numpy as np
import csv
import time

def covMatrix(filename,ndim):
    """
    通过协方差矩阵降维
    """
    n = 0
    s1 = np.zeros(ndim,dtype=np.double)
    s2 = np.zeros((ndim,ndim),dtype=np.double)

    with open(filename,'rt') as f:
        reader=csv.reader(f)
        for row in reader:
            r = np.array(row,dtype=np.double) 
            n += 1 
            s1 += r
            s2 += np.outer(r, r)
    s1 /= n
    s2 /= n
    s2 -= np.outer(s1, s1) #总体协方差
    #s2 *= (n/(n-1))   #样本协方差，无偏估计
    d = np.sqrt(s2.diagonal())
    s2 /= np.outer(d, d)  #归一化相关系数矩阵

    return s2

if __name__ == '__main__':
    print(covMatrix("../cov.txt",20))
